var myInterval;
var data=[];
$(function () {
    $MB.calenders('input[name="timeField"]', true, false);
    getUserCount();
    getMeetingRoomCount();
    getMeetingCount();
    getAttendeeCount();
    getDurationCount();
    getUserSate();
    initLineChart("cpuLineChart");
//    if(myInterval){
//          clearInterval(myInterval);
//    }
//    myInterval=setInterval(function () {
//      var k = document.cookie.indexOf(sessionId);
//      if(k==-1){
//           clearInterval(myInterval);
//           return;
//      }
//      if(document.getElementById("cpuLineChart")===null){
//           clearInterval(myInterval);
//           return;
//      }
//      getCpuUsage();
//    }, 1000*5);
     myInterval=setTimeout(function () {
            var k = document.cookie.indexOf(sessionId);
            if(k==-1){
                clearTimeout(myInterval);
                return;
            }
            if(document.getElementById("cpuLineChart")===null){
                clearTimeout(myInterval);
                return;
            }
            getCpuUsage();
            setTimeout(arguments.callee, 1000*5);
        }, 1000*5);
    $('#meetingTab li:first-child a').tab('show');
    $('#userGroupTab li:first-child a').tab('show');
    $('#meetingTab a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var activeTabId = $(e.target).attr('aria-controls');
        var title=$(e.target).text();
        var unit=$("#meetingTab div[data-toggle='buttons'] label.active input[type=radio]").val();
        getMeetingNum(activeTabId,title,unit);
    });
    $("#meetingTab div[data-toggle='buttons'] input[type=radio]").on("change",  function(){
          var unit=$(this).val();
          var activeTabId=$('#meetingTab li a.active').attr('aria-controls');
          var title=$('#meetingTab li a.active').text();
//          console.log(activeTabId);
          getMeetingNum(activeTabId,title,unit);
    });
    $('#userGroupTab a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var activeTabId = $(e.target).attr('aria-controls');
        var title=$(e.target).text();
        console.log(title);
        getCountByGroup(activeTabId,title);
    });
    getMeetingNum('meetingNum','会议数量','1');
    getCountByGroup('userGroup-meetingRoomNum','会议室');
    getSystemInfo();
});

function getUserCount(){
    $.get(ctx + "state/usersCount", {}, function (r) {
        if (r.code === 0) {
//            console.log(r.msg);
            var user=r.msg;
            $("#userCount").find(".count").find("span:first").html(user.userCount);
            $("#userCount").find(".more").find("span:first").html(user.userOnline);
            $("#userCount").find(".more").find("span").eq(1).html(user.guestCount);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function getMeetingRoomCount(){
    $.get(ctx + "state/meetingRoomCount", {}, function (r) {
        if (r.code === 0) {
//            console.log(r.msg);
            var meetingRoom=r.msg;
            var total=meetingRoom.total;
            var using=meetingRoom.usingCount;
            var pencent=Math.round(using / total * 10000) / 100.00 + "%";
            var usingStr="正在使用："+using+" 用量："+pencent;
            $("#meetingRoomCount").find(".count").find("span").html(total);
            $("#meetingRoomCount").find(".more").find("span").html(usingStr);
            names=[];
            names.push("有效");
            names.push("即将过期");
            names.push("已过期");
            meetingRooms = [];
            meetingRooms.push({
              value: meetingRoom.vaild,
              name: '有效'
            });
            meetingRooms.push({
              value: meetingRoom.vailding,
              name: '即将过期'
            });
            meetingRooms.push({
              value: meetingRoom.invaild,
              name: '已过期'
            });
            var colorData=['#48cda6','#fd87fb','#11abff'];
            var radius=['40%', '70%'];
            createPieChart("meetingRoomChart","会议室情况","会议室",total,colorData,radius,names,meetingRooms);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function getMeetingCount(){
    $.get(ctx + "state/meetingCount", {}, function (r) {
        if (r.code === 0) {
//            console.log(r.msg);
            var meeting=r.msg;
            var total=meeting.total;
            var using=meeting.usingCount;
            var pencent=Math.round(using / total * 10000) / 100.00 + "%";
            var usingStr="进行中会议："+using+" 用量："+pencent;
            $("#meetingCount").find(".count").find("span").html(total);
            $("#meetingCount").find(".more").find("span:first").html(usingStr);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}


function getAttendeeCount(){
    $.get(ctx + "state/attendeeCount", {}, function (r) {
        if (r.code === 0) {
//            console.log(r.msg);
            //meeting is null
            //modify by aaron.wei 2019.01.22
            var meeting=r.msg;
            var total= meeting ? meeting.totalUsers : 0;
            var avg=meeting ? meeting.avgUsers : 0;
            var joining=meeting ? meeting.joiningUsers : 0;
            $("#attendeeCount").find(".count").find("span").html(total);
            $("#attendeeCount").find(".more").find("span:first").html(avg);
            $("#attendeeCount").find(".more").find("span").eq(1).html(joining);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}


function getDurationCount(){
    $.get(ctx + "state/durationCount", {}, function (r) {
        if (r.code === 0) {
            // r.msg is null add by aaron.wei 2019.01.22
            var total=r.msg ? r.msg.total : 0;
            var avg=r.msg ? r.msg.avgCount : 0;
            $("#durationCount").find(".count").find("span.tpv-num").html(total);
            $("#durationCount").find(".more").find("span.tpv-num").html(avg);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}


function getUserSate(){
    $.get(ctx + "state/userState", {}, function (r) {
        if (r.code === 0) {
            var total=r.msg.total;
            var user=r.msg.userCount;
            var guest=r.msg.guestCount;
//            console.log('total:'+total+"-user:"+user+"-guest:"+guest);
            names=[];
            names.push("注册");
            names.push("临时");
            users = [];
            users.push({
              value: user,
              name: '注册'
            });
            users.push({
              value: guest,
              name: '临时'
            });
            var colorData=['#48cda6','#fd87fb'];
            var radius=['40%', '70%'];
            createPieChart("userChart","用户情况","用户",total,colorData,radius,names,users);
        } else {
            $MB.n_danger(r.msg);
        }
    });
}

function createPieChart(chartId,title,seriesTitle,total,colorData,radius,nameData,data){
    var chart = echarts.init(document.getElementById(chartId));
    var option = {
                title: {//标题组件
                    text: title,
                    subtext: total,
                    subtextStyle: {
                      color: '#436EEE',
                      align: 'right',
                      verticalAlign: 'middle'
                    },
                    top:'middle',
                    left:'24%',//标题的位置 默认是left，其余还有center、right属性
                    textStyle: {
                        color: "#436EEE",
                        fontSize: 17,
                    }
                },
                tooltip : { //提示框组件
                    trigger: 'item', //触发类型(饼状图片就是用这个)
                    formatter: "{a} <br/>{b} : {c} ({d}%)" //提示框浮层内容格式器
                },
                color: colorData,  //手动设置每个图例的颜色
                legend: {  //图例组件
                    //right:100,  //图例组件离右边的距离
                    orient : 'horizontal',  //布局  纵向布局 图例标记居文字的左边 vertical则反之
                    width:40,      //图行例组件的宽度,默认自适应
                    left: '70%',   //图例显示在右边
                    top: 'middle',   //图例在垂直方向上面显示居中
                    itemWidth:15,  //图例标记的图形宽度
                    itemHeight:15, //图例标记的图形高度
                    data:nameData,
//                    formatter: function(name){
//                        console.log(name);
//                        return name;
//                    },
                    textStyle:{    //图例文字的样式
                        color:'#333',  //文字颜色
                        fontSize:14    //文字大小
                    }
                },
                series : [ //系列列表
                    {
                        name: seriesTitle,  //系列名称
                        type:'pie',   //类型 pie表示饼图
                        center:['30%','50%'], //设置饼的原心坐标 不设置就会默认在中心的位置
                        radius : radius,  //饼图的半径,第一项是内半径,第二项是外半径,内半径为0就是真的饼,不是环形
                        itemStyle : {  //图形样式
                            normal : { //normal 是图形在默认状态下的样式；emphasis 是图形在高亮状态下的样式，比如在鼠标悬浮或者图例联动高亮时。
                                label : {  //饼图图形上的文本标签
                                    show : false  //平常不显示
                                },
                                labelLine : {     //标签的视觉引导线样式
                                    show : false  //平常不显示
                                }
                            },
                            emphasis : {   //normal 是图形在默认状态下的样式；emphasis 是图形在高亮状态下的样式，比如在鼠标悬浮或者图例联动高亮时。
                                label : {  //饼图图形上的文本标签
                                    show : true,
                                    position : 'center',
                                    textStyle : {
                                        fontSize : '10',
                                        fontWeight : 'bold'
                                    }
                                }
                            }
                        },
                        data:data
                    }
                ]
            };
            chart.setOption(option);
}
function getCpuUsage(){
   $.get(ctx + "actuator/metrics/system.cpu.usage", function (r,status) {
           if(status=="success"){
                 var cpuUsage=r.measurements[0].value;
                 var pencentVal=Math.round(r.measurements[0].value*100);
//                 console.log(pencentVal);
                  if(data.length>=15){
                      data.shift();
                      data.push(getData(pencentVal));
                  }else{
                    data.push(getData(pencentVal));
                  }
                  var myChart = echarts.init(document.getElementById("cpuLineChart"));
                  myChart.setOption({
                          series: [{
                              data: data
                          }]
                      });
           }else{
               clearTimeout(myInterval);
               $MB.n_danger(r.msg);
           }
       });
}
function initLineChart(ObjId){
   var chart = echarts.init(document.getElementById(ObjId));
   option = {
       color : [ '#0B62A4' ],
       tooltip: {
           trigger: 'axis'
       },
       xAxis: {
           type: 'time',
           splitLine: {
               show: false
           }
       },
       yAxis: {
          type: 'value',
          scale: true,
          max: 100,
          min: 0,
          splitNumber:5,
          boundaryGap: [0.2, 0.2],
          axisLabel:{
            formatter:'{value} %'
          }
       },
       series: [{
           type: 'line',
           showSymbol: false,
           hoverAnimation: false,
           data: data
       }]
   };
   chart.setOption(option);
}

function getData(val) {
    now = new Date();
//    var time =[now.getHours(),now.getMinutes() < 10 ?"0"+now.getMinutes():now.getMinutes(),now.getSeconds() <10 ?"0"+now.getSeconds():now.getSeconds()].join(':');
    value = val;
    return {
        name: now,
        value: [
            now,
            Math.round(value)
        ]
    }
}

function getMeetingNum(activeTab,title,unit){
      $.get(ctx + "state/meetingStats", {"activeTab":activeTab,"unit":unit,"timeField":""}, function (r) {
            if (r.code === 0) {
                var list=r.msg.numList;
//                 console.log(list);
                 var x_data=[];
                 var y_data=[];
                for(var i = 0; i < list.length; i++){
                    if(unit=='1'){ //24 hours
                        x_data.push(list[i].unit+":00");
                    }else if(unit=='2'){//wk 7day
                        switch (list[i].unit) {
                            case 0:
                                x_data.push("周一");
                                break;
                            case 1:
                                x_data.push("周二");
                                break;
                            case 2:
                                x_data.push("周三");
                                break;
                            case 3:
                                x_data.push("周四");
                                break;
                            case 4:
                                x_data.push("周五");
                                break;
                            case 5:
                                x_data.push("周六");
                                break;
                            case 6:
                                x_data.push("周日");
                                break;
                            default:
                                x_data.push(list[i].unit);
                                break;
                        }
                    }else if(unit=="3"){
                        x_data.push(list[i].unit+"日");
                    }else if(unit=='4'){
                        x_data.push(list[i].unit+"月");
                    }else {
                        x_data.push(list[i].unit);
                    }
                    y_data.push(list[i].num);
                }
                createBarChart(activeTab+"-container",title,x_data, y_data);
                var ranking=r.msg.meetingRootmList;
                createMeetingRoomRanking(activeTab+"-ranking",title,ranking)
            } else {
                $MB.n_danger(r.msg);
            }
        });
}

function createBarChart(ObjId,title,x_data,y_data) {
    var chart = echarts.init(document.getElementById(ObjId));
    chart.setOption({
        color : [ '#0B62A4' ],
        tooltip : {
            trigger : 'axis',
            axisPointer : { // 坐标轴指示器，坐标轴触发有效
                type : 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
        },
        legend : {
            data : [ title ]
        },
        grid : {
            left : '3%',
            right : '10%',
            bottom : '10%',
            containLabel : true
        },
        xAxis : [ {
            type : 'category',
            data : x_data,
        } ],
        yAxis:[ {
            type: 'value',
            scale: true,
            name: title,
            max: Math.max.apply(null, y_data)+5,
            min: 0,
            splitNumber:5,
            boundaryGap: [0.2, 0.2]
        } ],
        series : [ {
            name : title,
            type : 'bar',
            barWidth : '60%',
            data : y_data
        } ]
    }, true);
}

function createMeetingRoomRanking(ObjId,title,contentArray){
        var ulObj=$("#"+ObjId+" .list-group");
        ulObj.empty();
        for(var i = 0; i < contentArray.length; i++){
             var id=title+"_li"+i;
             var htmlStr="<li id="+id+">";
             if(i<3){
               htmlStr+="<span class='badge badge-primary badge-pill'>"+(i+1)+"</span>";
             }else{
               htmlStr+="<span class='badge badge-default badge-pill'>"+(i+1)+"</span>";
             }
              htmlStr+="<div style='margin-left:20px;width:200px;'>"+contentArray[i].meeting_room_name+"</div><span class='badge badge-default' style='margin-left:150px;'>"+contentArray[i].count+"</span></li>";
              ulObj.append(htmlStr);
             $("#"+id).attr("class",'list-group-item');
        }
}


function getCountByGroup(ObjId,title,type){
    $.get(ctx + "state/statsByGroup", {"activeTab":ObjId}, function (r) {
         if (r.code === 0) {
             console.log(r.msg);
             var list=r.msg;
             var total=0;
             var radius=["55%","70%"];
             var colorData=[];
             var nameData=[];
             var data=[];
             for(var i = 0; i < list.length; i++){
                 var name=list[i].groupName;
                 var count=list[i].count;
//                 var red = parseInt(Math.random()*254).toString(16);
//                 var blue = parseInt(Math.random()*254).toString(16);
//                 var green= parseInt(Math.random()*254).toString(16);
//                 var color = '#'+red+blue+green;
                 colorData.push(getRandomColor);
                 nameData.push(name);
                 data.push({value: count,name: name});
                 total+=count;
             }
             createPieChart(ObjId+"-container",title,title,total,colorData,radius,nameData,data)
         }else{
            $MB.n_danger(r.msg);
         }
    });
}

var getRandomColor = function(){
    return  '#' + (function(color){
         return (color +=  '0123456789abcdef'[Math.floor(Math.random()*16)])
         && (color.length == 6) ?  color : arguments.callee(color);
    })('');
 }


function getSystemInfo(){
    //os name :/actuator/env/os.name
    //cpu num: actuator/env/NUMBER_OF_PROCESSORS
//    $.get(ctx + "state/systemInfo", function (r) {
//         if (r.code === 0) {
//            console.log(r.msg);
//            var totalMem=r.msg.totalPhysicalMemorySize;
//            var usageMem=
//         }else{
//            $MB.n_danger(r.msg);
//         }
//    });
    var fun1 = $.ajax({url: ctx + "state/systemInfo",type:'GET',dataType:'json'}),
        fun2 = $.ajax({url: ctx + "actuator/env/os.name",type:'GET',dataType:'json'}),
        fun3 = $.ajax({url: ctx + "actuator/health",type:'GET',dataType:'json'});
    $.when(fun1,fun2,fun3).then(function(data1,data2,data3){
            console.log(data1);
            console.log(data2);
            console.log(data3);
            var totalMem=data1[0].msg.totalPhysicalMemorySize;
            var freeMem=data1[0].msg.freePhysicalMemorySize;
            var usageMem=data1[0].msg.usagePhysicalMemorySize;
            var cpuNum=data1[0].msg.availableProcessors;
            var ip=data1[0].msg.hostAddress;
            var city=data1[0].msg.city;
            var osName=data2[0].property.value;
            var systemStatus=data3[0].status;
            var totalSpace=(data3[0].details.diskSpace.details.total/1024/1024/1024).toFixed(2);
            var freeSpace=(data3[0].details.diskSpace.details.free/1024/1024/1024).toFixed(2);
            var usageSpace=((Number(data3[0].details.diskSpace.details.total)-Number(data3[0].details.diskSpace.details.free))/1024/1024/1024).toFixed(2)
            $("#memInfo").text(totalMem);
            $("#cpuInfo").text(cpuNum);
            $("#spaceInfo").text(totalSpace);
            $("#osName").text(osName);
            $("#ip").text(ip);
            $("#city").text(city);
            if(systemStatus=='UP'){
              $("#systemStatus").text("正常运行");
              $("#systemStatus").css("color","green");
            }else{
              $("#systemStatus").text("系统异常");
              $("#systemStatus").css("color","red");
            }
            memNames=[];
            memNames.push("已使用");
            memNames.push("剩余");
            memDatas = [];
            memDatas.push({
              value: usageMem,
              name: '已使用'
            });
            memDatas.push({
              value: freeMem,
              name: '剩余'
            });
            var memColorData=['#839b5c','#d6d6d6'];
            var radius=['55%', '70%'];
            createPieChart("memInfoPie","RAM","RAM", (Math.round(usageMem / totalMem * 10000) / 100.00 + "%"),memColorData,radius,memNames,memDatas);
            spaceDatas = [];
            spaceDatas.push({
              value: usageSpace,
              name: '已使用'
            });
            spaceDatas.push({
              value: freeSpace,
              name: '剩余'
            });
            var spaceColorData=['#fcc800','#d6d6d6'];
            createPieChart("spaceInfoPie","Storage","Storage", (Math.round(usageSpace / totalSpace * 10000) / 100.00 + "%"),spaceColorData,radius,memNames,spaceDatas);
        },function(){
            $MB.n_danger("request error!!!");
        })

}